<template>
  <template
    v-if="
      hasOneShowingChild(props.item?.children, props.item) &&
      (!onlyOneChild.children || onlyOneChild.noShowingChildren)
    "
  >
    <a-menu-item
      :key="resolvePath(onlyOneChild.path)"
      :path="resolvePath(onlyOneChild.path)"
    >
      <template #icon>
        <component :is="props.item.meta?.icon"></component>
      </template>
      <div>
        {{ props.item.meta.title }}
      </div>
    </a-menu-item>
  </template>
  <template v-else>
    <a-sub-menu
      :key="resolvePath(props.item.path)"
      :title="item.meta?.title"
      class="text-[15px]"
    >
    <template #icon>
        <component :is="props.item.meta?.icon"></component>
      </template>
      <!-- <template #icon>
        <img class="w-[16px] h-[16px]" v-if="showIcon" :src="onIcon(item.meta?.icon)" />
      </template> -->
      <sidebarItem
        v-for="child in props.item.children"
        :key="child.path"
        :item="child"
        :base-path="child.path"
        class="text-[14px]"
      >
      </sidebarItem>
    </a-sub-menu>
  </template>
</template>

<script setup lang="ts">
const props = defineProps<{
  item: any;
  basePath: string;
}>();

const onlyOneChild = ref<any>(null);

const hasOneShowingChild = (children: any[], parent: any) => {
  if (!children) {
    children = [];
  }
  const showingChildren = children.filter((item: any) => {
    onlyOneChild.value = item;
    return true;
  });
  if (showingChildren[0]?.meta?.showParent) {
    return false;
  }
  if (showingChildren.length === 1) {
    return true;
  }
  if (showingChildren.length === 0) {
    onlyOneChild.value = { ...parent, path: "", noShowingChildren: true };
    return true;
  }
  return false;
};

const resolvePath = (routePath: string) => {
  const httpReg = /^http(s?):\/\//;
  if (httpReg.test(routePath) || httpReg.test(props.basePath)) {
    return routePath || props.basePath;
  } else {
    // 使用path.posix.resolve替代path.resolve 避免windows环境下使用electron出现盘符问题
    return routePath || props.basePath;
  }
};
</script>

<style lang="less" scoped></style>
